//
//  HELMeVC.m
//  HandheldELearn
//
//  Created by wsj2015 on 2017/1/6.
//  Copyright © 2017年 陈武琦. All rights reserved.
//

#import "HELMeVC.h"
#import "UIView+WZLBadge.h"

#import "BTMeCell.h"
#import "HELMeHeader.h"
#import "UIViewController+WXSTransition.h"
#import "BTLoginVC.h"
//#import "HELCompulsoryVC.h"
#import "HELExamVC.h"
//#import "HELSigninVC.h"
#import "HELMeSettingVC.h"
#import "HELPersonInformationVC.h"
#import "UIButton+WebCache.h"
#import "UIView+WZLBadge.h"
//#import "HELMeetingInfo.h"
//#import "HELMyDownloadVC.h"
#import "HELNavigationController.h"
#import "HELMyCourseListVC.h"
#import "HELMyExamVC.h"
#import "HELMessageListVC.h"
#import "HELCreditVC.h"
#import "HELMyCollectCourseList.h"
#import "HELCouponVC.h"
#import "MessageServicer.h"
#import "HELOrderListVC.h"
#import "HELSpecialistlistVC.h"
@interface HELMeVC ()<UIImagePickerControllerDelegate,UIAlertViewDelegate>



@property(nonatomic, strong) UIButton *messageBtn;

@property (nonatomic,  strong) HELMeHeader *header;

@end

@implementation HELMeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)configUI{
    
//    @"我的订单"
    self.dataArray = [@[@[@"我的课程",@"我的考试",@"我的收藏",@"我的专家"]] copy];
    
   
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-49);
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"BTMeCell" bundle:nil] forCellReuseIdentifier:@"BTMeCell"];
    self.tableView.alwaysBounceVertical = NO;
    HELMeHeader *header =[HELMeHeader header];
   
    self.header = header;
    
    CGFloat f = kScreenFactor;
    header.frame =CGRectMake(0, 0, kScreenWidth, f * 246);
    
    self.tableView.tableHeaderView = header;
    
    [self setupNavItems];
    
    weakSelf_define;
    header.logBlock = ^(){
        if ([HELAppManager userInfo]) {
            return ;
        }
        BTLoginVC *logVC =[BTLoginVC new];
        HELNavigationController *nav =[[HELNavigationController alloc] initWithRootViewController:logVC
                                      ];
        [weakSelf wxs_presentViewController:nav animationType:WXSTransitionAnimationTypeSysCubeFromLeft completion:nil];
        
    };
    
    header.changeHeader = ^(){
        if ([HELAppManager userInfo] ) {
            [weakSelf headPhotoClick];
        }
    };
    header.personInfoBlock = ^(){
        [weakSelf.navigationController setNavigationBarHidden:NO animated:YES];
         [weakSelf.navigationController pushViewController:[HELPersonInformationVC new] animated:YES];
        
    };
    header.scoreRecordBlock = ^(){
      
        [weakSelf.navigationController pushViewController:[HELCreditVC new] animated:YES];
    };
      HELUser *user = [HELAppManager  userInfo];
    if (user) {
        [self sucessLogin];
    }
    //监听登陆和退出登陆消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sucessLogin) name:LoginSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout) name:LogoutNotification object:nil];

}




- (void)messageNot{
    HELMessageListVC *meetingInfoVC = [HELMessageListVC new];

    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:meetingInfoVC animated:YES];
    
}


//展示头像
- (void)sucessLogin{
    
    HELUser *user = [HELAppManager userInfo];
    
    if (user && user.headImage) {
       
        
        [self.header.iconBtn sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[HELNetworkManager sharedMg].bathURL,user.headImage]] forState:UIControlStateNormal];
    }else{
        [self.header.iconBtn setImage:[UIImage imageNamed:@"default-icon"] forState:UIControlStateNormal];
        
    }
    
    [UIView animateWithDuration:.6 animations:^{
        self.header.iconBtn.transform = CGAffineTransformScale(self.header.transform, 1.4, 1.4);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:.6 delay:0 usingSpringWithDamping:.6 initialSpringVelocity:.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
            self.header.iconBtn.transform = CGAffineTransformIdentity;
        } completion:nil];
    }];
    
    [self.header.loginBtn setTitle:user.realName?user.realName:user.realName forState:UIControlStateNormal];
    [self queryAppStatus];
}


- (void)queryAppStatus{

   
    weakSelf_define;
    [[HELNetworkManager sharedMg] GET:helIosAppStatus parameters:nil success:^(id responseObject) {
        
        if (responseObject[@"data"]  && ![responseObject[@"data"] isKindOfClass:[NSNull class]]) {
            if ( ![responseObject[@"data"][@"value"] isEqualToString:@"REVIEW"]) {
                weakSelf.dataArray = [@[@[@"我的课程",@"我的考试",@"我的收藏",@"我的专家"],@[@"我的订单",@"优惠劵"]] copy];
                
                [weakSelf.tableView reloadData];
            }
        }
        
       
        
    } failure:^(NSString *err) {
        
    }];

}




- (void)logout{
    
    [self.header.iconBtn setImage:[UIImage imageNamed:@"hard"] forState:UIControlStateNormal];
    [self.header.loginBtn setTitle:@"登录" forState:UIControlStateNormal];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    weakSelf_define;
    [[MessageServicer shareServicer] requestPersonInfoWithSucess:^(NSInteger unread) {
        
        unread >0?[weakSelf.messageBtn resumeBadge]:[weakSelf.messageBtn clearBadge];
        
    }];
        
   
}
- (void)setupNavItems {
    
    
    UIButton *settingBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 40, 40)];
    [settingBtn setImage:[UIImage imageNamed:@"设置"] forState:UIControlStateNormal];
    [settingBtn addTarget:self action:@selector(settingPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settingBtn];
    self.tableView.backgroundColor = kTableView_bg;
    self.tableView.tableFooterView = [UIView new];
    UIButton *noticeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 50, 20, 40, 40)];
    [noticeBtn setImage:[UIImage imageNamed:@"消息"] forState:UIControlStateNormal];
    [noticeBtn addTarget:self action:@selector(messageNot) forControlEvents:UIControlEventTouchUpInside];
      noticeBtn.badgeBgColor = [UIColor whiteColor];
    [noticeBtn showBadgeWithStyle:WBadgeStyleRedDot value:1 animationType:WBadgeAnimTypeBreathe];
    noticeBtn.badgeCenterOffset = CGPointMake(-8, 10);
    self.messageBtn = noticeBtn;
    [self.view addSubview:noticeBtn];
    
}

- (void)settingPress {
    HELMeSettingVC *settingVC = [[HELMeSettingVC alloc] init];
    //    settingVC.userInfoModel = self.userInfo;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:settingVC animated:YES];
    
}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return [self.dataArray[section] count];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    
    BTMeCell *cell= [tableView dequeueReusableCellWithIdentifier:@"BTMeCell"];
    NSString *title = self.dataArray[indexPath.section][indexPath.row];
    cell.title.text = title;
    cell.separatorInset = UIEdgeInsetsMake(0, 49, 0, 10);
    UIView *view = [UIView new];
    view.alpha = .7;
    view.frame = cell.bounds;
    view.backgroundColor = kMainColor;
    cell.selectedBackgroundView =view;
    
    cell.leftIcon.image =[UIImage imageNamed:title];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
   
    if (indexPath.section == 0) {
//         [self.navigationController setNavigationBarHidden:NO animated:YES];
        switch (indexPath.row) {
            case 0:{
                

                [self.navigationController setNavigationBarHidden:NO animated:YES];
                [self.navigationController pushViewController:[HELMyCourseListVC new] animated:YES];
            }
                break;
            case 1:{
                HELMyExamVC *electVC = [HELMyExamVC new] ;
                [self.navigationController setNavigationBarHidden:NO animated:YES];
                [self.navigationController pushViewController:electVC animated:YES];
                
            }
                
                break;
            case 2:{
                HELMyCollectCourseList *electVC = [HELMyCollectCourseList new] ;
                 [self.navigationController setNavigationBarHidden:NO animated:YES];
                [self.navigationController pushViewController:electVC animated:YES];
               
                break;
            }
            case 3:{
                HELSpecialistlistVC *electVC = [HELSpecialistlistVC new] ;
                [self.navigationController setNavigationBarHidden:NO animated:YES];
                [self.navigationController pushViewController:electVC animated:YES];
                
                
            }
                
                
                break;
                
            default:
                break;
        }
        
    }else{
        switch (indexPath.row) {
            case 0:{
                [self.navigationController setNavigationBarHidden:NO animated:YES];
                HELOrderListVC *orderVC = [HELOrderListVC new];
                
                [self.navigationController pushViewController:orderVC animated:YES];
                break;
            }
                
          
            case 1:{
                [self.navigationController setNavigationBarHidden:NO animated:YES];
                //                HELSigninVC *signinVC = [HELSigninVC new];
                //                signinVC.title = @"签到课程";
                //                [self.navigationController pushViewController:signinVC animated:YES];
                
                
                [self.navigationController pushViewController:[HELCouponVC new] animated:YES];
              
                break;
            }
                
            default:
                break;
               
        }
      
    
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view =[UIView new];
    view.backgroundColor =[UIColor clearColor];
    view.frame = CGRectMake(0, 0, kScreenWidth, 20);
    return  view;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return  15;
}
#pragma mark -------------headPhotoClick--------------------
- (void)headPhotoClick {
    
    UIActionSheet *actionSheetView = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册" ,nil];
    [actionSheetView showInView:self.navigationController.view];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else if(buttonIndex == 1){
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }
    
}
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = info[UIImagePickerControllerEditedImage];
   
    [self uploadHeadPhoto:img];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
/*
  *上传头像
  */
- (void)uploadHeadPhoto:(UIImage *)image{
//    __block MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.header animated:YES];
//    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
//    hud.animationType = MBProgressHUDAnimationZoomIn;
//    hud.detailsLabelText = @"正在上传...";
//    hud.progress = 0;
//    [hud show:YES];
    
  
    weakSelf_define;
    
    cwqHud(self.view);
    
    
    [[HELNetworkManager sharedMg] UPLOAD:helUploadHeadPhotofoUrl parameters:nil image:image progress:^(CGFloat percent) {
//        dispatch_sync(dispatch_get_main_queue(), ^{
////            hud.progress = percent;
//            NSLog(@"%@",@(percent));
//        });
       
    } success:^(id responseObject) {
        [hud hide:YES];
        if (!responseObject[@"data"]) {
//            cwqHudRequestError([responseObject[@"err"] isKindOfClass:[NSString class]]?responseObject[@"err"]:@"未知错误");
        }else {
            cwqHudSuccess(@"上传成功~");
          
          
            [weakSelf updateUserInfoWithPhoto:responseObject[@"data"]];
         
        }
    } failure:^(NSString *err) {
         [hud hide:YES];
        cwqHudRequestError(err);
    }];
    
}
/*
 *修改个人信息
 */

- (void)updateUserInfoWithPhoto:(NSString *)photo {
    __block HELUser *userInfo = [HELAppManager userInfo];
    if (!userInfo) {
        alertMessage(@"用户id获取失败");
        return;
    }
    weakSelf_define;
    cwqHud(self.view);
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];

   
    param[@"headImage"] = photo;
    
    
   
    
    [[HELNetworkManager sharedMg] PUT_JSON:helUpdateUserInfoUrl parameters:param progress:nil success:^(id response) {
        
        [hud hide:YES];
        userInfo.headImage =photo;
        [HELAppManager saveUseInfo:[userInfo mj_keyValues]];
        [weakSelf sucessLogin];
        cwqHudSuccess(@"保存成功~");
    } failure:^(NSString *err) {
        [hud hide:YES];
        if ([err isKindOfClass:[NSString class]]) {
            cwqHudRequestError(err);
        }
    }];
    
//    [[HELNetworkManager sharedMg] GET:helUpdateUserInfoUrl parameters:param success:^(id responseObject) {
//        [hud hide:YES];
//        if (responseObject[@"err"]) {
//           
//        }else {
//            cwqHudSuccess(@"保存成功");
//            [weakSelf updateLocalUserInfo:photo];
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//        
//        
//    } failure:^(NSString *err) {
//         [hud hide:YES];
//        cwqHudRequestError(err);
//        
//    }];
    
}
#pragma -mark 同步本地信息
- (void)updateLocalUserInfo:(NSString *)photoId {
    
//    helUserInfo
//    if (photoId && ![userInfo.photo isEqualToString:photoId]) {
//        userInfo.photo = photoId;
//        NSString *baseURL = [[[HELNetworkManager sharedMg] getBaseUrl] stringByAppendingString:@"/upload/userphoto/"];
////        userInfo.photoShowMap = newInfo.photoShowMap;
//        userInfo.photoShowMap.mini = [baseURL stringByAppendingString:photoId];
//    }
// 
//    NSMutableDictionary *dict = [[userInfo mj_keyValues] mutableCopy];
//    [HELAppManager saveUseInfo:dict];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //[self.header scrollerChangeImageWithoffsetY:scrollView.contentOffset.y];
}


@end
